import { useRequest, useTitle } from 'ahooks';
import { Spin } from 'antd';
import { FC, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useParams } from 'react-router-dom';
import { renderRoutes, RouteConfigComponentProps } from 'react-router-config';

import { pathMatch, questionAnswerQuestionPathObj } from 'src/route';
import * as APIS from '../../constants/api-constants';
import {
  initQuestionnaireAction,
  startPageLoadingAction,
  stopPageLoadingAction
} from './actions';
import styles from './index.module.less';

const isQuestionProcess = (
  path: string
) => pathMatch(path, questionAnswerQuestionPathObj.path);

const PageLoading: FC = ({ children }) => {
  const { pageLoading } = useSelector((
    storeState: QA.ReduxState
  ) => ({
    pageLoading: storeState.pageLoading
  }));

  return <Spin size="large" spinning={pageLoading}>{children}</Spin>;
};

const Main = ({ route }: RouteConfigComponentProps) => {
  const history = useHistory();
  const dispatch = useDispatch();
  const { container } = styles;
  const { questionnaireUuid } = useParams<{
    questionnaireUuid: string
  }>();
  const { run, loading } = useRequest((uuid) => ({
    url: APIS.QUESTIONNAIRE_ANSWER_DETAIL,
    method: 'GET',
    params: { uuid }
  }), {
    manual: true,
    onSuccess: (res) => {
      const questionnaireBasic: QA.QuestionnaireInitBaisc = res.data;

      if (!questionnaireBasic?.open) {
        history.push(`/questionAnswer/home/${questionnaireUuid}/closeResult`);
        return;
      }

      // 如果之前的 url 是问卷的题目，则不跳转到验证页
      if (!isQuestionProcess(history.location.pathname)) {
        dispatch(initQuestionnaireAction(questionnaireBasic));
        history.push(`/questionAnswer/home/${questionnaireUuid}/verfication`);
      }
    },
    onError: () => {
      history.push(`/questionAnswer/home/${questionnaireUuid}/closeResult`);
    },
  });

  useEffect(() => {
    run(questionnaireUuid);
  }, [questionnaireUuid]);

  useEffect(() => {
    if (loading) dispatch(startPageLoadingAction());
    else dispatch(stopPageLoadingAction());
  }, [loading]);

  useTitle('心理健康问卷');

  return (
    <PageLoading>
      <div className={container}>
        {renderRoutes(route?.routes) ?? null}
      </div>
    </PageLoading>

  );
};

export default Main;
